package main

import "fmt"

//演示类型断言的用法
type Usb interface {
	Start()
	Stop()
}

type Camera struct {
}

func (c Camera) Start() {
	fmt.Println("相机开始工作")
}

func (c Camera) Stop() {
	fmt.Println("相机停止工作")
}

type Phone struct {
}

func (p Phone) Start() {
	fmt.Println("手机开始工作")
}

func (p Phone) Stop() {
	fmt.Println("手机停止工作")
}

func (p Phone) Charge() {
	fmt.Println("手机开始充电")
}

func main() {
	var devices []Usb
	devices = append(devices, Camera{})
	devices = append(devices, Phone{})

	//panic: interface conversion: main.Usb is main.Camera, not main.Phone
	p := devices[0].(Phone) //如果类型不匹配，直接报错
	p.Start()

	for _, v := range devices {
		if p, ok := v.(Phone); ok { //增加第二个返回值ok之后不会报错
			p.Start()
			p.Stop()
			p.Charge()
			continue
		}

		if c, ok := v.(Camera); ok {
			c.Start()
			c.Stop()
		}

	}
}
